﻿using HHG.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace OnLineExam.Web.handler
{
    /// <summary>
    /// UploadHandler 的摘要说明
    /// </summary>
    public class UploadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            var path = context.Request.Params["path"];
            if (!path.HasValue())
                path =  "/Upload/other";
            else
            {
                path = "/Upload/"+ path ;
            }
            try
            {
                System.IO.Directory.CreateDirectory(context.Server.MapPath(path));
            }
            catch (Exception)
            {


            }

            var result = new UploadResult ();
             
            string fileNewName = string.Empty;
            //这里只能用<input type="file" />才能有效果,因为服务器控件是HttpInputFile类型
            HttpFileCollection files = context.Request.Files;
            if (files.Count > 0)
            {
                //设置文件名
                fileNewName =  DateTime.Now.ToString("yyyyMMddHHmmssff") + "_" + System.IO.Path.GetFileName(files[0].FileName);
				//保存文件
				 
				files[0].SaveAs(context.Server.MapPath(path) + "/" + fileNewName);



                result = new UploadResult(0, "文件上传成功！", new Data(path+ "/"+fileNewName,System.IO.Path.GetFileNameWithoutExtension( fileNewName)));
            }
            else
			{
				result = new UploadResult(111, "文件上传失败！", new Data());
				 
            }
            context.Response.Write(result.SerializeObject());
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        public class Data
        {
            /// <summary>
            /// 图片路径
            /// </summary>
            public string src { get; set; }
            /// <summary>
            /// 图片名称
            /// </summary>
            public string title { get; set; }

            public Data() { }
            public Data(string src,string title) { this.src = src;this.title = title; }
        }

        public class UploadResult
        {
            /// <summary>
            /// 
            /// </summary>
            public int code { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string msg { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public Data data { get; set; }

            public UploadResult() { }

            public UploadResult(int code,string msg,Data data) {
                this.code = code; this.msg = msg;this.data = data;
            }
        }

    }


}